<template>
  <el-card class="mt-10">
    <el-button type="primary" :icon="Plus" @click="addAttr" :disabled="flag"
      >添加属性</el-button
    >
    <el-table :data="attrList" border>
      <el-table-column
        label="序号"
        type="index"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column
        label="属性名称"
        prop="attrName"
        width="150"
      ></el-table-column>
      <el-table-column label="属性值列表">
        <template v-slot="{ row }">
          <el-tag
            class="ml-2"
            type="success"
            v-for="attrValue in row.attrValueList"
            :key="attrValue.id"
            >{{ attrValue.valueName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="{ row }">
          <el-button
            :icon="Edit"
            type="warning"
            size="small"
            @click="updateAttr(row)"
            title="修改"
          ></el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="delAttr(row.id)">
            <template #reference>
              <el-button
                :icon="Delete"
                type="danger"
                size="small"
                title="删除"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AttrList",
};
</script>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";
import { getAttrListApi, deleteAttrApi } from "@/api/product/attr";
import { AttrList, AttrItem } from "@/api/product/type/attrType";
const flag = ref(true);
const categoryStore = useCategoryStore();
const attrStore = useAttrStore();
const attrList = ref<AttrList>([]);
const emit = defineEmits(["setIsShow"]);
const addAttr = () => {
  emit("setIsShow", false);
  // 重置pinia数据
  attrStore.$reset();
};
// 封装获取属性列表
const getAttrList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
};
// 删除一条数据
const delAttr = async (index: number) => {
  await deleteAttrApi(index);
  attrList.value.splice(index, 1);
  getAttrList();
};
// 修改属性
const updateAttr = (row: AttrItem) => {
  emit("setIsShow", false);
  console.log(row);
  attrStore.attr = row;
};
// 当category3Id发生变化是才获取属性值
watch(
  () => categoryStore.category3Id,
  async (category3Id) => {
    if (!category3Id) {
      attrList.value = [];
      flag.value = true;
      return;
    }
    flag.value = false;
    getAttrList();
  },
  { immediate: true }
);
</script>

<style scoped></style>
